package com.zxy.leetcode._00000_00099._00000_00009;

/**
 * https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 *
 * 给定一个字符串，请你找出其中不含有重复字符的 最长子串 的长度。
 *
 * 算法：滑动窗口
 */
public class Test00003 {

    public static void main(String[] args) {
        Test00003 test = new Test00003();
        System.out.println(test.lengthOfLongestSubstring("ab"));
        System.out.println(test.lengthOfLongestSubstring("ab") == 2);
        System.out.println(test.lengthOfLongestSubstring("aab"));
        System.out.println(test.lengthOfLongestSubstring("aab") == 2);
        System.out.println(test.lengthOfLongestSubstring("abcabcbb") == 3);
        System.out.println(test.lengthOfLongestSubstring("bbbbb"));
        System.out.println(test.lengthOfLongestSubstring("bbbbb") == 1);
        System.out.println(test.lengthOfLongestSubstring("pwwkew"));
        System.out.println(test.lengthOfLongestSubstring("pwwkew") == 3);
        System.out.println(test.lengthOfLongestSubstring("") == 0);
    }

    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        if (s.length() == 1) {
            return 1;
        }

        int max = 1;
        int left = 0;
        int length = s.length();

        while (left < length-1) {
            // 小优化，已经可以不需要再进行下去了
            if (length - left < max) {
                break;
            }
            for (int right=left+1; right<length; right++) {
                if (!check(s, left, right)) {
                    if (right - left > max) {
                        max = right - left;
                    }
                    break;
                }
                // 最后一个了，前面还没被拦截下来，这里要做最终计算了
                if (right == length - 1) {
                    if (right - left + 1 > max) {
                        max = right - left + 1;
                    }
                }
            }
            left ++;
        }

        return max;
    }

    // 是否满足要求的子串，没有重复的
    public boolean check(String s, int left, int right) {
        for (int i = left; i<=right-1; i++) {
            // 根据前面的指针移动，除了最后一个，其他都是校验过的了，所以只需要校验最后一个即可
            if (s.charAt(right) == s.charAt(i)) {
                return false;
            }
        }

        return true;
    }

}
